const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const check = require('../../utils/check.js');
// const RSA = require('../../utils/wxapp_rsa.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbar_bgcolor: wx.getStorageSync('navbar_bgcolor'),
    carModel: '',
    birth: '',
    info: {
      name: '',
      gender: '0',
      birth: '',
      phone: '',
      address: '',
      cardType: 'A',
      cardNo: '',
      nationality: '汉'
    },
    gender: ['', '男', '女'],
    genderIndex: 1,
    cardType: [{
      id: 'A',
      name: 'A：居民身份证'
    }, {
      id: 'C',
      name: 'C：军官证'
    }, {
      id: 'D',
      name: 'D：士兵证'
    }, {
      id: 'E',
      name: 'E：军官离退休证'
    }, {
      id: 'F',
      name: 'F：境外人员身份证明'
    }, {
      id: 'G',
      name: 'G：外交人员身份证明'
    }, {
      id: 'I',
      name: 'I：外国人永久居留身份证'
    }, {
      id: 'Q',
      name: 'Q：港澳台居民居住证'
    }],
    cardTypeIndex: 0,
    dialogShow: false,
    buttons: [{ text: '取消' }, { text: '识别并应用' }],
    cardimg1: '../../style/images/card1.png',
    cardimg1Sign: false,
    cardName: '',
    cardNo: '',
    endDate: '',
    schoolId: '',
    schoolName: '',
    zsid:'',
     //公钥
    //  publicKey:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var carModel = wx.getStorageSync("carModel");
    console.log("当前用户选择的驾考类型是："+carModel);

    var currentDate = new Date();
    var end = currentDate.getFullYear() + '-' + currentDate.getMonth() + 1 + '-' + currentDate.getDate();
    this.setData({
      carModel: options.carModel,
      endDate: end,
      schoolId: options.schoolId ? options.schoolId : '',
      schoolName: options.schoolName ? options.schoolName : ''
    });

    // console.log("ysxm:::::根据用户的ID，获取用户的填写过的基本信息");
    let that = this;


    var userid = wx.getStorageSync("userid");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    /*
    util.request(api.queryinfobyId, {uid:userid,key:api.key}).then(function (res) {
      if(res.errno === 402){
        wx.showModal({
          title: '错误',
          content:'不被允许的请求',
          showCancel: false
        })
        return;
      }
      // console.log("sss::::"+JSON.stringify(res));
      var errno = res.errno;
      if(errno != 500){
      //console.log(res.data);
      //console.log(res.data.name);
      that.setData({
        info:res.data
      })
      var birthday = res.data.birth;
      //console.log("lxdh:birthday:::"+birthday);
      that.setData({
        birth:birthday,
        ['info.cardType']:'A'
      })
    }

    });*/
    // this.getPublicKey();
  },
  // getPublicKey:function(e){
  //   var that = this;
  //   util.request(api.getPublickey,{},"POST").then(function (res) {
  //     that.data.publicKey = res.data
  //   })
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  ageNow:function(birthday){
    // var birthday = '2005-01-12';
		if(birthday){
      birthday=birthday.split('-');
      // 新建日期对象
      let date = new Date();
      // 今天日期，数组，同 birthday
      let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
      // 分别计算年月日差值
      let age = today.map((val, index) => {
          return val - birthday[index]
      })
      // 当天数为负数时，月减 1，天数加上月总天数
      if (age[2] < 0) {
          // 简单获取上个月总天数的方法，不会错
          let lastMonth = new Date(today[0], today[1], 0)
          age[1]--
          age[2] += lastMonth.getDate()
      }
      // 当月数为负数时，年减 1，月数加上 12
      if (age[1] < 0) {
          age[0]--
          age[1] += 12
      }
      // console.log(age[0]+'岁'+age[1]+'月'+age[2]+'天');
      return age[0];
    }
    // return age;
  },
  //信息保存
  bindSave: function (e) {
    var that = this;
    var name = that.data.info.name;
    var address = that.data.info.address;
    var phone = that.data.info.phone;
    var cardNo = that.data.info.cardNo;
    var code = e.detail.value.code;
    var nationality = that.data.info.nationality;

    if (name == "") {
      wx.showModal({
        title: '提示',
        content: '请填写姓名',
        showCancel: false
      })
      return;
    }
    if (that.data.info.gender == "") {
      wx.showModal({
        title: '提示',
        content: '请填写性别',
        showCancel: false
      })
      return;
    }
    if (!cardNo) {
      wx.showModal({
        title: '提示',
        content: '请填写证件号码',
        showCancel: false
      })
      return;
    } else if (that.data.info.cardType == 'A') {//身份证号
      if (check.isValidIdCard(cardNo) == false) {
        wx.showModal({
          title: '提示',
          content: '请填写正确的证件号码',
          showCancel: false
        })
        return;
      }
    }
    if(this.data.info.gender == ''){
      wx.showModal({
        title: '提示',
        content: '性别不能为空',
        showCancel: false
      })
      return;
    }
    if(this.data.info.birth == ''){
      wx.showModal({
        title: '提示',
        content: '出生日期不能为空',
        showCancel: false
      })
      return;
    }
    var age = this.ageNow(this.data.info.birth);
    // console.log("age:::::::"+age);
    if(age < 18){
      wx.showModal({
        title: '提示',
        content: '报名年龄需要大于18周岁！',
        showCancel: false
      })
      return;
    }
    if (phone.length == 0) {  //2020-09-12 未上线，短信功能不可使用
    //if (phone.length == 0) {
      wx.showModal({
        title: '提示',
        content: '手机号不能为空',  //2020-09-12 未上线，短信功能不可使用 手机号和验证码不能为空
        showCancel: false
      });
      return false;
    }

    
    /**
     * 手机号码验证
     */
    if (!check.isValidPhone(phone)) {
      wx.showModal({
        title: '提示',
        content: '请填写合法手机号',
        showCancel: false
      })
      return;
    }
    

    /**
     * 判定民族是否合法
     */
    if (nationality) {
      if (check.isValidNations(nationality) == false) {
        wx.showModal({
          title: '提示',
          content: '请填写正确的民族',
          showCancel: false
        })
        return;
      }
    }


    var userid = wx.getStorageSync("userid");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    //进行判断当前用户是否是有推荐用户
    var zsid = wx.getStorageSync("zsid");
    if(zsid != ''){
      this.setData({
        zsid:zsid
      })
    }


    //console.log("yushuaixm::::::"+userid);
    //取消判断验证码
    // var encrypt_rsa = new RSA.RSAKey();
    // encrypt_rsa = RSA.KEYUTIL.getKey(that.data.publicKey);
    // var encryptedData = encrypt_rsa.encrypt(that.data.info.cardNo)
    // encryptedData = RSA.hex2b64(encryptedData)
    // var mobile = encrypt_rsa.encrypt(phone)
    // mobile = RSA.hex2b64(mobile)
    util.request(api.signUpSave, {
      name: name,
      cardType: that.data.info.cardType,
      cardNo: that.data.info.cardNo,
      gender: that.data.genderIndex,
      birth: that.data.info.birth,
      address: address,
      mobile: phone,
      // code: code,
      trainType: that.data.carModel,
      nationality: that.data.info.nationality,
      schoolId: that.data.schoolId,
      schoolName: that.data.schoolName,
      uid:userid,
      zsid:zsid
    }, "POST")
      .then(function (res) {
        //console.log("yushuaixm:::::33333:"+userid);
        //console.log("yushuaixm:::::33333:"+JSON.stringify(res));
        /*wx.redirectTo({
          url: 'selectClass',
        })
        return;*/
        if (res.errno == 0) {
          wx.redirectTo({
            url: 'selectClass',
          })
          //体检标识  2020.11.14 流程调整，填写完信息后直接进行选班，体检放置缴费后完成
          /*var step = res.data;
          switch(step){
            case 'A': //无体检信息，进行体检指引
              wx.navigateTo({
                url: 'healthNotice',
              })
              break;
            case 'C': //体检通过，进行选班
              wx.navigateTo({
                url: 'selectClass',
              })
              break;
            case 'D': //体检不通过 报名终止
              wx.navigateTo({
                url: 'noPass',
              })
              break;
            default:
              break;
          }*/
        } else {
         // util.showErrorToast(res.errmsg);
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          });
        }
      });
  },
  bindDateChange: function (e) {
    this.setData({
      birth: e.detail.value,
      [`info.birth`]: e.detail.value
    })
  },
  bindGenderChange: function (e) {
    console.log(e.detail.value);
    this.setData({
      genderIndex: e.detail.value,
      [`info.gender`]: e.detail.value
    })
  },
  bindCardType: function (e) {
    var that = this;
    var index = e.detail.value;
    that.setData({
      cardTypeIndex: index,
      [`info.cardType`]: that.data.cardType[index].id,
      [`info.cardNo`]: ''
    })
  },
  toIdentification: function () {
    wx.navigateTo({
      url: 'ocr_idcard',
    })
  },
  bindMobileInput: function (e) {
    this.setData({
      [`info.phone`]: e.detail.value
    });
  },
  bindAddrInput: function (e) {
    this.setData({
      [`info.address`]: e.detail.value
    });
  },
  //姓名输入去除空格
  bindNameInput: function (e) {
    this.setData({
      [`info.name`]: e.detail.value.replace(/\s+/g, '')
    });
  },
  IdCard:function(IdCard, type) {
    if (type === 1) {
        //获取出生日期
        let birthday = IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14)
        return birthday
    }
    if (type === 2) {
        //获取性别
        if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
            return "1"
        } else {
            return "2"
        }
    }
},
  bindCardNoInput: function (e) {
    var val = e.detail.value;
    var birth = "";
    var sex = "";
    if(val.length == 18){
      birth = this.IdCard(val,1);
      sex = this.IdCard(val,2);
      // console.log(sex);
    }
    this.setData({
      [`info.cardNo`]: val,
      birth:birth,
      [`info.birth`]:birth,
      genderIndex:sex,
      [`info.gender`]:sex
    });
  },
  bindNationalityInput: function (e) {
    this.setData({
      [`info.nationality`]: e.detail.value
    });
  },
  authorize() {
    wx.navigateTo({
      url: `faceWebview/faceWebview`
    })
  },
  //获取验证码
  sendCode: function () {
    var that = this;

    //① 手机号验证为空、合法
    if (that.data.info.phone.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '手机号不能为空',
        showCancel: false
      });
      return false;
    }

    if (!check.isValidPhone(that.data.info.phone)) {
      wx.showModal({
        title: '错误信息',
        content: '手机号输入不正确',
        showCancel: false
      });
      return false;
    }
    //② 发送验证码
    wx.request({
      url: api.AuthRegisterCaptcha,
      data: {
        mobile: that.data.info.phone
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.errno == 0) {
          wx.showModal({
            title: '发送成功',
            content: '验证码已发送',
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  openConfirm: function () {
    this.setData({
      dialogShow: true
    })
  },
  tapDialogButton(e) {
    var that = this;
    //console.log(e.detail.index);//0为取消  1为确认
    var index = e.detail.index;
    if (index == 1) {//确认
      if (that.data.cardimg1Sign == false) {
        wx.showModal({
          title: '提示',
          content: '请上传证件进行识别！',
          showCancel: false
        })
        return;
      }

      util.request(api.signUpOcr, {
        url: that.data.cardimg1
        //url: 'https://www.rzsjpkythfwpt.com/wx/storage/fetch/ud8yuyn3a0vntqlaa2lc.jpg'
      })
        .then(function (res) {
          if (res.errno === 0) {
            var _res = res.data;
            var name = _res.name;//姓名
            var no = _res.id;//身份证号
            var birth = that.getBirthdatByIdNo(no);//出生日期
            console.log(birth);
            var addr = _res.addr;//地址
            var gender = _res.gender;//性别
            var nationality = _res.nationality;//民族
            if (name.length == 0 || no.length == 0) {
              wx.showModal({
                title: '提示',
                content: '未识别到身份信息，请重新上传！',
                showCancel: false
              })
              return;
            }
            if (name == 'null' || no == 'null') {
              wx.showModal({
                title: '提示',
                content: '未识别到身份信息，请重新上传！',
                showCancel: false
              })
              return;
            }
            that.setData({
              [`info.name`]: name,
              [`info.cardNo`]: no,
              [`info.address`]: addr,
              [`info.gender`]: gender == '男' ? 1 : 2,
              [`info.nationality`]: nationality,
              [`info.birth`]: birth,
              birth: birth,
              genderIndex: gender == '男' ? 1 : 2,
              dialogShow: false,
              cardName: '',
              cardNo: '',
              cardimg1: '../../style/images/card1.png',
              cardimg1Sign: false,
            })
            return

          } else {
            wx.showModal({
              title: '提示',
              content: '未识别到身份信息，请重新上传！',
              showCancel: false
            })
            return
          }
        }).catch(function () {
          wx.showModal({
            title: '提示',
            content: '未识别到身份信息，请重新上传！',
            showCancel: false
          })
          return
        });
      return
    }
    this.setData({
      dialogShow: false,
      [`info.cardName`]: '',
      [`info.cardNo`]: '',
      cardimg1: '../../style/images/card1.png',
      cardimg1Sign: false,
    })

  },
  //上传身份证人像面
  uploadCard1: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        if (!that.checkImageFormat(tempFilePaths[0])) {
          wx.showModal({
            title: '提示',
            content: '上传了不被允许的文件格式,只允许jpg,jpeg,png格式',
            showCancel: false
          })
          return;
        }
        wx.uploadFile({
          url: api.CardStorageUpload,
          filePath: tempFilePaths[0],
          name: 'file',
          formData:{
            key:api.key
          },
          success(res) {
            var _res = JSON.parse(res.data);
            if (_res.errno === 0) {
              var url = _res.data.url
              that.setData({
                cardimg1: url,
                cardimg1Sign: true
              });
            }
          },
          fail(res) {
            wx.showModal({
              title: '错误',
              content: '上传失败',
              showCancel: false
            })
          }
        })

      }
    })
  },
   //照片格式校验
   checkImageFormat: function (filePath) {
    var regExp = /\.(jpg|jpeg|png)$/;
    return regExp.test(filePath);
  }, 
  delCardFile:function(){

  },
  //验证身份证号并获取出生日期
  getBirthdatByIdNo: function (idCard) {
    var birthday = "";
    if (idCard != null && idCard != "") {
      if (idCard.length == 15) {
        birthday = "19" + idCard.substr(6, 6);
      } else if (idCard.length == 18) {
        birthday = idCard.substr(6, 8);
      }

      birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
    }

    return birthday;
  }

})